/**
 * Copyright (c) 2006-2016 Huize Ltd. All Rights Reserved. 
 *  
 * This code is the confidential and proprietary information of   
 * Hzins. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with Huize,http://www.huize.com.
 *  
 */
package com.agan.concurrent;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author hz1412988
 * @date 2018年2月5日 上午11:33:25
 * @version
 */
public class SemaphoreTest {

    public static void main(String[] args) {
	/** 定义窗口个数 **/
	final Semaphore semaphore = new Semaphore(2);

	ExecutorService executor = Executors.newCachedThreadPool();
	/** 模拟10个用户 **/
	for (int i = 1; i <= 10; i++) {
	    final int offset = i;
	    executor.execute(new Runnable() {

		@Override
		public void run() {
		    try {
			/** 获取信号量许可 **/
			semaphore.acquire();
			System.out.println(Thread.currentThread().getName() + "用户【" + offset + "】进入窗口，准备买票");
			TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
			System.out.println(Thread.currentThread().getName() + "用户【" + offset + "】买票完成，即将离开");
			TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
			System.out.println(Thread.currentThread().getName() + "用户【" + offset + "】离开售票窗口-->还有" + semaphore.getQueueLength() + "个人在等待排队");
			semaphore.release();
		    } catch (InterruptedException e) {
			e.printStackTrace();
		    }
		}

	    });
	}
	executor.shutdown();
    }
}
